
package ee.siimoliver.chat.utils;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;

import javax.swing.AbstractAction;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.text.JTextComponent;

public class ChatUtils {
	
	public static void deleteFiles(String... files) {
		for (String fileName : files) {
			new File(fileName).delete();
		}
	}
	
	public static boolean fileSystemHasFile(String directory, String fileName) {
		for (File f : new File(directory).listFiles()) {
			if (!f.isDirectory() && f.getName().equalsIgnoreCase(fileName)) {
				return true;
			}
		}
		return false;
	}
	
	public static String encodeString(String input, boolean selfEncoder) {
		if (selfEncoder) {
			StringBuffer sb = new StringBuffer();
			for (char c : input.toCharArray()) {
				switch (c) {
				case ' ':
					sb.append(Const.NBSP);
					break;
				case '\n':
					sb.append(Const.NWLN);
					break;
				default:
					sb.append(c);
					break;
				}
			}
			return sb.toString();
		} else {
			try {
				int questionPos = input.indexOf(Const.QUESTION_MARK) + 1;
				String request = input.substring(0, questionPos);
				return request + URLEncoder.encode(input.substring(questionPos), Const.UTF8);
			} catch (UnsupportedEncodingException e) {
				return null; //not going to happen
			}
		}
	}
	
	public static String decodeString(String input, boolean selfDecoder) {
		if (selfDecoder) {
			return input.replaceAll(Const.NBSP, " ").replaceAll(Const.NWLN, "\n");
		} else {
			try {
				return URLDecoder.decode(input, Const.UTF8);
			} catch (UnsupportedEncodingException e) {
				return null; //not going to happen
			}
		}
	}
	
	public static void makeGETRequestPrintResponse(String request) throws IOException {
		URLConnection connection = (new URL(request)).openConnection();
		connection.setConnectTimeout(Const.TIMEOUT_IN_MILLIS);
		BufferedReader bfr = new BufferedReader(new InputStreamReader(
				connection.getInputStream()));
		String line;
		while ((line = bfr.readLine()) != null) {
			System.out.println(line);
		}
		bfr.close();
	}
	
	public static String getMyIpPort() throws IOException {
		return InetAddress.getLocalHost().getHostAddress() + ":" +
				ApplicationProperties.getInstance().getProperty(Const.PROP_PORT);
	}
	
	/**
	 * Centers window.
	 * @param target - frame to center
	 */
	public static void centerWindow(Window target) {
		Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
		target.setLocation((int) (dim.getWidth() / 2 - (double) target.getWidth() / 2),
				(int) (dim.getHeight() / 2 - (double) target.getHeight() / 2));
	}
	
	public static void centerWindowRelativeToParent(Window target, Window parent) {
		Point location = parent.getLocation();
		location.x += (double) parent.getWidth() / 2.0 - (double) target.getWidth() / 2.0;
		location.y += (double) parent.getHeight() / 2.0 - (double) target.getHeight() / 2.0;
		target.setLocation(location);
	}
	/**
	 * Map action to enter.
	 * @param component - component from where the action is fired when clicked the enter button
	 * @param button - button who's action will be fired
	 */
	public static void mapActionToEnter(JComponent component, final JButton button) {
		component.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter");
		component.getActionMap().put("enter", new AbstractAction() {
			private static final long serialVersionUID = 1L;
			@Override
			public void actionPerformed(ActionEvent e) {
				button.doClick();
			}
		});
	}
	/**
	 * Map action to enter.
	 * @param component - component from where the action is fired when clicked the enter button
	 * @param button - button who's action will be fired
	 */
	public static void mapInputActionToEnter(final JTextComponent component, final JButton button) {
		component.getInputMap().put(KeyStroke.getKeyStroke("ENTER"), "enter");
		component.getActionMap().put("enter", new AbstractAction() {
			private static final long serialVersionUID = 1L;
			@Override
			public void actionPerformed(ActionEvent e) {
				if (!component.getText().trim().isEmpty()) {
					button.doClick();
				}
			}
		});
	}
	
	public static void setPlatformSpecificLookAndFeel() {
		try {
			UIManager.setLookAndFeel(
			        UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			System.err.println("Unable to set platform specific look and feel");
		}
	}
}
